/*
 * @Author: TC(tengchao@taqu.cn)
 * @Date: 2025-11-04 16:24:53
 * @Last Modified by: TC(tengchao@taqu.cn)
 * @Last Modified time: 2025-11-04 17:44:00
 */

import { _decorator, Component, RenderTexture, MeshRenderer, director, Node, v2, v3 } from "cc";
const { ccclass, property } = _decorator;

/**
 * 描边后处理
 */
@ccclass("ShaderCaseWater")
export class ShaderCaseWater extends Component {
    @property(RenderTexture)
    renderTexture: RenderTexture;

    @property(Node)
    nodeRole: Node = null;

    private _worldPos = v3();

    start() {
        const material = this.node.getComponent(MeshRenderer).getMaterialInstance(0);
        material.setProperty("depthTexture", this.renderTexture.window.framebuffer.depthStencilTexture);
        const pass0 = material.passes[0];
        const bindingIndex = pass0.getBinding("depthTexture");
        pass0.bindSampler(bindingIndex, director.root.pipeline.globalDSManager.pointSampler);

        material.setProperty("scaleU", this.node.scale.x);
        material.setProperty("scaleV", this.node.scale.z);
    }

    protected update(dt: number): void {
        this.node.getWorldPosition(this._worldPos);
        if (!this.nodeRole) return;

        //this.nodeRole为与水面产生交互的节点,案例中的小乌龟
        const roleWorldPos = this.nodeRole.worldPosition.clone();
        const localPos = v3();
        //this.node即为水面节点
        this.node.inverseTransformPoint(localPos, roleWorldPos);

        //其中10是默认Plane的尺寸，
        //+0.5因为shader的uv坐标原点在左上角。
        const uvRole = v2(localPos.x / 10 + 0.5, localPos.z / 10 + 0.5);
        const material = this.node.getComponent(MeshRenderer).getMaterialInstance(0);
        material.setProperty("rolePos", uvRole);

        const dir = this.nodeRole.forward;
        material.setProperty("roleForward", v2(dir.x, dir.z));
    }
}
